#!/usr/bin/env python
#coding=utf-8

#
# Min Feng 02/15/08
#
#


import os
import sys
import re
import dbf
import copy

def loadTableM(f, c):
	_name, _type, _recs = loadTableL(f)
	
	_map = {}
	for _r in _recs:
		_map[str(_r[_name.index(c)]).strip()] = _r
	
	return _name, _type, _map

def loadTableL(f):
	_name, _type, _f = loadTableR(f)
	
	return _name, _type, list(_f)

def loadTableR(f):
	_f = dbf.dbfreader(file(f, 'rb'))
	
	_name = _f.next()
	_type = _f.next()
	
	return _name, _type, _f	

def addTable(f, fc, t, tc, o):
	print 'loading source table...',
	_fn, _ft, _fl = loadTableL(f)
	print 'ok'
	
	print 'loading addition table...',
	_tn, _tt, _tm = loadTableM(t, tc)
	print 'ok'
	
	print '-----------------------------------'
	
	_an = copy.copy(_fn)
	_at = copy.copy(_ft)
	_al = []
	
	for i in range(len(_tn)):
		if _tn[i] not in _an and _tn[i] != tc:
			_an.append(_tn[i])
			_at.append(_tt[i])
	
	_logf = []
	for i in range(len(_fl)):
		_fr = _fl[i]
		_id = str(_fr[_fn.index(fc)]).strip()
		
		print '(' + str(i + 1) + '/' + str(len(_fl)) + ')', _id,
		
		_tr = None
		if _id in _tm:
			_tr = _tm[_id]
			_logf.append(_id)
			print '\tnot found'
		else:
			print 'ok'
		
		_l = []
		for j in range(len(_an)):
			if _an[j] in _fn:
				_l.append(_fr[_fn.index(_an[j])])
			elif _tr and _an[j] in _tn:
				_l.append(_tr[_tn.index(_an[j])])
			else:
				_l.append('')
		
		_al.append(_l)
	
	print 'saving ...',
	dbf.dbfwriter(file(o, 'wb'), _an, _at, _al)
	print 'ok'
	
	if _logf:
		print 'saving failure log...',
		file('not.found.log', 'w').write(repr(_logf))
		print 'ok'
		
if __name__ == '__main__':
	if len(sys.argv) != 2:
		print """Adding fire attribute v 0.1 02/15/2008
Usage:
	attribute.add.py [input shapefile]
		"""
	else:
		_inputFile = sys.argv[1]
		_outputPath = _inputFile
		
		addTable(_inputFile, 'fireId', 'all_fire_decrip.dbf', 'FIRE_ID', _outputPath)
	